const events = {}

function log() {
  // console.debug(...arguments)
}

export default {
  on(name, handler) {
    log(`on(${name})`)
    const handlers = events[name] || []
    events[name] = handlers
    handlers.push(handler)
  },
  off(name, handler) {
    log(`off(${name})`)
    const handlers = events[name]
    if (!handlers) {
      return
    }
    const idx = handlers.indexOf(handler)
    if (idx === -1) {
      return;
    }
    handlers.splice(idx, 1)
  },
  once(name, handler) {
    log(`once(${name})`)
    const handlers = events[name] || []
    events[name] = handlers
    handlers.push(handler)
    handler.__once__ = true
  },
  emit(name, args) {
    log(`emit(${name})`)
    const handlers = events[name]
    if (!handlers) {
      return
    }
    // remove the ONCE handlers
    events[name] = handlers.filter(handler => !handler.__once__)

    for (const handler of handlers) {
      handler(args)
    }
  }
}
